package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Employee;
import com.itheima.common.R;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author Tang
 * @date 2023/2/20
 */
@Slf4j
@RequestMapping("/employee")
@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        if (password == null) {
            return R.error("密码不能为空！");
        }
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(wrapper);

        //3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("该用户不存在！");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!pwd.equals(emp.getPassword())){
            return R.error("用户名密码不匹配！");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果 0代表禁用 1正常
        if (emp.getStatus() == 0) {
            return R.error("该员工已被禁用！");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        session.setAttribute("employeeId", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        //1.清理session中的id
        session.invalidate();

        //2.返回结果
        return R.success("退出成功！");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> addEmployee(@RequestBody Employee employee, HttpSession session) {
        //优化：新增员工之前，判断该用户名是否已经存在数据库中
        /*LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(wrapper);
        if (one != null) {
            //return R.error("该用户名【"+employee.getUsername()+"】已存在！");
            throw new CustomException("该用户名【"+employee.getUsername()+"】已存在！");
        }*/

        //1.补齐字段
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //优化：公共字段自动填充
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        Long employeeId = (Long) session.getAttribute("employeeId");
        employee.setCreateUser(employeeId);
        employee.setUpdateUser(employeeId);*/

        //2.调用service新增方法
        boolean flag = employeeService.save(employee);

        //3.返回结果
        return flag ? R.success("新增成功！") : R.error("新增失败！");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer pageSize, String name){
        //0.添加分页拦截器
        //1.设置分页对象 Page对象
        Page<Employee> employeePage = new Page<>(page, pageSize);

        //2.设置查询条件
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Employee::getName, name);

        //3.调用service的分页查询方法
        employeeService.page(employeePage, wrapper);

        //4.返回结果
        return R.success(employeePage);
    }

    /**
     * 员工启用|禁用  + 员工编辑
     * @param employee
     * @param session
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpSession session) {
        log.info("EmployeeController 的线程id:{}",Thread.currentThread().getId());
        //编辑员工：优化
        //在更新员工信息之前，先查询员工表，判断当前修改的用户名是否存在（根据前端传递的用户名查询，注意：要排除它自生数据）
        /*if (employee.getUsername() != null) {  //如果有用户名，说明在做编辑操作
            LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Employee::getUsername, employee.getUsername());
            wrapper.ne(Employee::getId, employee.getId());
            int count = employeeService.count(wrapper);
            if (count > 0) {
                throw new CustomException("该用户名【"+employee.getUsername()+"】已存在！");
            }
        }*/

        //1.补齐更新时间和更新人
        //优化：公共字段自动填充
        /*employee.setUpdateTime(LocalDateTime.now());
        Long employeeId = (Long) session.getAttribute("employeeId");
        employee.setUpdateUser(employeeId);*/

        //2.调用service更新方法根据id更新
        boolean flag = employeeService.updateById(employee);

        //3.返回结果
        return flag ? R.success("修改成功！") : R.error("修改失败！");
    }

    /**
     * 根据员工id查询员工信息（回显）
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        //1.调用service的查询方法（根据id查询）
        Employee employee = employeeService.getById(id);
        //2.返回结果
        return R.success(employee);
    }
}
